﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace UIControls
{
    /// <summary>
    /// Interaction logic for NumberTextbox.xaml
    /// </summary>
    public partial class NumberTextbox : TextBox
    {
        public NumberTextbox()
        {
            InitializeComponent();
        }

        private void TextBox_PreviewKeyDown(object sender, KeyEventArgs e)
        {

        }

        public double MaxValue { get; set; }
        public double MinValue
        {
            get { return double.Parse(GetValue(MinValueProperty).ToString()); }
            set { SetValue(MinValueProperty, value); }
        }
        /// <summary>
        /// Gets and sets the currently viewed date
        /// </summary>
        public static readonly DependencyProperty MinValueProperty =
            DependencyProperty.Register("MinValue", typeof(double), typeof(NumberTextbox),null);

        private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            TextBox textBox = sender as TextBox;
            int iValue = -1;

            if (Int32.TryParse(textBox.Text, out iValue) == false)
            {
                TextChange textChange = e.Changes.ElementAt<TextChange>(0);
                int iAddedLength = textChange.AddedLength;
                int iOffset = textChange.Offset;

                textBox.Text = textBox.Text.Remove(iOffset, iAddedLength);

                if (textBox.Text == "")
                {
                    textBox.Text = MinValue.ToString();
                }
            }
            if (iValue < MinValue) textBox.Text = MinValue.ToString();
        }
    }
}
